package com.example.mam.web;

import com.example.mam.dto.BaseResult;
import com.example.mam.entity.User;
import com.example.mam.exception.BizExceptionEnum;
import com.example.mam.exception.BizExceptionMessage;
import com.example.mam.service.UserService;
import com.example.mam.shiro.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author muncie [muncie.hoo@qq.com]
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping()
    public BaseResult<Object> addUser(User user) {
        Long id = userService.addUser(user);
        return new BaseResult<>(true, id);
    }


    /**
     *
     * @param username   邮箱
     * @param password  密码
     * @returnBaseResult
     */
    @GetMapping("/login")
    public BaseResult<Object> login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            if (UnknownAccountException.class.getName().equals(e.getClass().getName())) {
                return new BaseResult<>(false, new BizExceptionMessage(BizExceptionEnum.INVALID_USER));
            }
            if (IncorrectCredentialsException.class.getName().equals(e.getClass().getName())) {
                return new BaseResult<>(false, new BizExceptionMessage(BizExceptionEnum.INVALID_PASSWORD));
            }
            return new BaseResult<>(false, new BizExceptionMessage(BizExceptionEnum.LOGIN_ERROR));
        }
        return new BaseResult<>(true, null);
    }

    @RequiresUser
    @GetMapping("/current")
    public BaseResult<Object> getCurrentUser() {
        return new BaseResult<>(true, userService.getUserById(ShiroUtil.getCurrentUserId()));
    }

    @GetMapping("/{id}")
    public BaseResult<Object> getUserById(@PathVariable("id") Long userId) {
        return new BaseResult<>(true, userService.getUserById(userId));
    }

    /**
     * 登出
     *
     * @return
     */
    @RequiresUser
    @GetMapping("/logout")
    public BaseResult<Object> logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return new BaseResult<>(true, null);
    }
}
